﻿Imports DotNetNuke.Services.Scheduling
Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.Services.Search
Imports DotNetNuke.Entities.Portals

Namespace Aricie.DNN.Modules.LuceneSearch.Business.Scheduling
    Public Class ScheduledIndexation
        Inherits SchedulerClient

        Public Sub New(objScheduleHistoryItem As ScheduleHistoryItem)
            MyBase.ScheduleHistoryItem = objScheduleHistoryItem
        End Sub

        Public Overrides Sub DoWork()

            Dim additionnalStringForLog As String = "<br />"

            Try
                Progressing()
                Status = "Currently indexing data"
                Dim searchItemInfoCollection As New SearchItemInfoCollection()
                Dim portalController As New PortalController
                Dim LSD As New LuceneSearchDataStore()
                For Each portalInformation As PortalInfo In portalController.GetPortals()
                    If portalInformation.ExpiryDate = New Date() OrElse (portalInformation.ExpiryDate <> New Date() AndAlso (portalInformation.ExpiryDate) > Date.Now) Then
                        'The current portal isn't expired. We have to index its content.
                        Status = "Indexing portal " & portalInformation.PortalName
                        ScheduleHistoryItem.AddLogNote(additionnalStringForLog & "Indexing portal: " & portalInformation.PortalName)
                        LSD.StoreSearchItems(LuceneIndexer.RetrieveSearchIndexItems(portalInformation.PortalID), portalInformation.PortalID)
                    End If
                Next

                ' les opérations sont terminées, on vide tout
                LuceneIndexer.ThisThreadHandlesSearchIndexationAndStorage = False
                LuceneIndexer.ThreadPickedUpForRunningIndexation = False

                Status = "Data indexation done"
                ScheduleHistoryItem.Succeeded = True
                ScheduleHistoryItem.AddLogNote(additionnalStringForLog & "Data indexation done!")
            Catch ex As Exception
                ScheduleHistoryItem.Succeeded = False
                ScheduleHistoryItem.AddLogNote(additionnalStringForLog & "Data indexation failed! Error:" + ex.Message)
                ScheduleHistoryItem.AddLogNote(additionnalStringForLog & "Location: " + ex.StackTrace)
                Errored(ex)
                Exceptions.LogException(ex)
            End Try
        End Sub
    End Class
End Namespace